package com.cn.threadpool;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.atomic.AtomicLong;

/**
 * FUN:
 * 
 * @author sushy
 * @date 2016-3-23
 */
public class MyRejectedExecutionHandler extends CallerRunsPolicy implements RejectedExecutionHandler {
	private boolean isCallerRuns = true;
	private AtomicLong rejectedTimes = new AtomicLong(0);// 拒绝请求次数
	private String rejectedErrMsg;// 拒绝请求反馈的错误信息

	public MyRejectedExecutionHandler(boolean isCallerRuns, String rejectedErrMsg) {
		this.isCallerRuns = isCallerRuns;
		this.rejectedErrMsg = rejectedErrMsg;
	}

	public long getRejectedTimes() {
		return rejectedTimes.get();
	}

	public String getRejectedErrMsg() {
		return rejectedErrMsg;
	}

	public void setRejectedErrMsg(String rejectedErrMsg) {
		this.rejectedErrMsg = rejectedErrMsg;
	};

	public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
		rejectedTimes.incrementAndGet();// 增加拒绝请求次数
		boolean isPaused = false;
		if (e instanceof MyThreadPoolExecutor) {
			MyThreadPoolExecutor crmExe = (MyThreadPoolExecutor) e;
			isPaused = crmExe.isPaused();
		}
		if (isCallerRuns && isPaused == false) {
			super.rejectedExecution(r, e);
			return;
		}
		throw new RejectedExecutionException(rejectedErrMsg);
	}

}
